package user03.handler;

import cn.hutool.json.JSONUtil;
import common05.common.Results;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Slf4j
public class SecurityAuthenticationHandler implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
        String username = SecurityContextHolder.getContext().getAuthentication().getName();
        log.error("您没有登录！url=[{}] ip=[{}] username=[{}]  exception=[{}]", request.getRequestURI(), request.getRemoteAddr(), username, e.getMessage());
        PrintWriter writer = response.getWriter();
        writer.write(JSONUtil.toJsonStr(Results.unauthorized()));
        writer.flush();
        writer.close();
    }

}
